<template>
  <div>
    <div :id="id" :class="className" :style="{height:(height-40)+'px',width:width}" />
    <div :id="`${id}1`" :style="{height:(height*0.66)+'px',width:width}" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import { throttle, parseTime, subtract, downFixed, upFixed } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    yName: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    data22: {
      type: Array,
      default: () => {
        return []
      }
    },
    contrastIndex_obj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    contrastIndexRisk_obj: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chart: null,
      chart1: null,
      listLoading: false,
      xDate: [],
      data_obj1: {},
      data_obj2: {},
      data1: []
    }
  },
  watch: {
    data: {
      handler(newValue) {
        this.data = newValue
        this.xDate = this.data.map(item => item.networthTime)
        this.data1 = this.data.map(item => item.networthValue)
        this.data_obj1[this.yName] = this.data1

        const data2_1 = this.data22.map(item => item.drawDown)
        this.data_obj2 = {}
        this.data_obj2[this.yName] = data2_1

        this.$nextTick(() => {
          if(this.chart) {
            this.chart.dispose()
            this.chart1.dispose()
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }else {
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }
        })
      },
      deep: true,
      immediate: true
    },
    contrastIndex_obj: {
      handler(newValue) {
        this.data_obj1 = {}
        this.data_obj1[this.yName] = this.data1
        // this.data_obj1['净值'] = this.data1
        Object.keys(newValue).forEach(key => {
          const item = newValue[key]
          this.data_obj1[key] = item.map(item => item.indexValue)
        })
        this.$nextTick(() => {
          if(this.chart) {
            this.chart.dispose()
            this.chart1.dispose()
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }else {
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }
        })
      },
      deep: true,
      immediate: true
    },
    contrastIndexRisk_obj: {
      handler(newValue) {
        this.data_obj2 = {}
        const data2_1 = this.data22.map(item => item.drawDown)
        this.data_obj2[this.yName] = data2_1
        Object.keys(newValue).forEach(key => {
          const item = newValue[key]
          this.data_obj2[key] = item.map(item => item.drawDown)
        })
        this.$nextTick(() => {
          if(this.chart) {
            this.chart.dispose()
            this.chart1.dispose()
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }else {
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  created() {

  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    this.chart1.dispose()
    this.chart1 = null
  },
  methods: {
    initChart(xDate, obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      const color_list = ['rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(238,203,87,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)'] //todo 颜色 
      const color_list_a = ['rgba(225,103,86,0.2)', 'rgba(129,183,236,0.2)', 'rgba(238,203,87,0.2)', 'rgba(173,224,255,0.2)', 'rgba(255,155,203,0.2)'] //todo 颜色
      const series1 = []
      const series2 = []
      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          const item = obj1[key]
          series1.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            data: item
          })
        })
      }

      if(Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          const item = obj2[key]
          series2.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            itemStyle: {
              color: color_list[i]
            },
            lineStyle: {
              width: 1.6
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: i ? 'rgba(0,0,0,0)' : color_list_a[i]
              }, {
                offset: 1,
                color: i ? 'rgba(0,0,0,0)' : color_list[i]
              }])
            },
            data: item
          })
        })
      }

      this.chart.setOption({
        title: {
          left: 'left',
          text: '收益'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter: (params) => {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${parseTime(params[0].name)}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span>
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}${(typeof params[i].data)=='number' ? '%' : ''}</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '15%',
          left: 120,
          right: '20%',
          bottom: '10%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '10%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          }
        },
        calculable: true,
        xAxis: [{
          show: false,
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto',
          },
          data: xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          type: 'slider',
          show: false,
          start: 0,
          end: 100
        }, {
          show: false,
          start: 0,
          end: 100,
          realtime: true,
          height: '6%',
          bottom: '8%',
        }],
        series: series1
      })

      this.chart1.setOption({
        title: {
          left: 'left',
          text: '回撤'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${parseTime(params[0].name)}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}${(typeof params[i].data)=='number' ? '%' : ''}</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '4.5%',
          left: 120,
          right: '20%',
          bottom: '36%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '2%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          }
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          axisLine: {
            show: false,
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false,
            alignWithLabel: true
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            margin: 20,
            interval: 'auto'
          },
          data: xDate
        }],
        yAxis: [
          {
            type: 'value',
            splitNumber: 4,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value + '%'
              }
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          realtime: true, // 实时更新系列的视图
          height: '8%',
          bottom: '5%',
        }],
        series: series2
      })

      this.chart1.on('datazoom', throttle((params) => {       
        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const op = this.chart.getOption()
        const op1 = this.chart1.getOption()
        Object.keys(this.data_obj1).forEach((key, i) => {
          const list = this.data_obj1[key]
          if(list.length-1 >= baseline_i) {
            const baseline_val = this.data_obj1[key][baseline_i]
            const data = list.map(item => {
              if(item != '') {
                // return (Number(divide(item, baseline_val))+1).toFixed(5)
                return (Number(subtract(item, baseline_val))+1).toFixed(5)
              }else if(item == '') {
                return ''
              }
            })
            op.series[i].data = data
          }
        })
        op.dataZoom[0].start = op1.dataZoom[0].start
        op.dataZoom[0].end = op1.dataZoom[0].end
        op.dataZoom[1].start = op1.dataZoom[1].start
        op.dataZoom[1].end = op1.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      }, 500))
    },
  }
}
</script>
